﻿/******************************************************************************
 * 【本类功能概述】                                 					      *
 *  版权所有（C）2017- 匠梦科技                                         *
 *  保留所有权利。                                                            *
 ******************************************************************************
 *  作者 : <hughjk>
 *  创建时间:2019年5月19日 14:59:28
 *  文件描述:扩展代码
 *****************************************************************************/

using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;

namespace Util
{
    public class SerializeJosn
    {
        /// <summary>
        /// 序列化 对象到字符串    
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string Serialize<T>(T obj)
        {
            if (obj.isNull())
            {
                debug.log("Serialize obj is null!!!");
                return "";
            }
            if (obj.isT<string>())
            {
                return obj.ToString();
            }
            try
            {
                return JsonMapper.ToJson(obj);
            }
            catch (Exception ex)
            {
                debug.log("序列化失败,原因:" + ex.Message);
                return "";
            }
        }

        /// <summary>
        /// 反序列化 字符串到对象
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <param name="str">要转换为对象的字符串</param>
        /// <returns>反序列化出来的对象</returns>
        public static T Desrialize<T>(string str)
        {
            T obj = default(T);
            if (str.isTrue())
            {
                if (typeof(T) == typeof(string))
                {
                    obj = (T)(object)str;
                    return obj;
                }
                try
                {
                    obj = JsonMapper.ToObject<T>(str);
                }
                catch (Exception ex)
                {
                    debug.log("反序列化失败,原因:" + ex.Message);
                }
            }
            return obj;
        }

    }

    public class SerializeObj
    {
        /// <summary>
        /// 序列化 对象到字符串
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string Serialize<T>(T obj)
        {
            if (obj.isNull())
            {
                debug.log("Serialize obj is null!!!");
                return "";
            }
            try
            {
                IFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                stream.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            {
                throw new Exception("序列化失败,原因:" + ex.Message);
            }
        }

        /// <summary>
        /// 反序列化 字符串到对象
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <param name="str">要转换为对象的字符串</param>
        /// <returns>反序列化出来的对象</returns>
        public static T Desrialize<T>(string str)
        {
            T obj = default(T);
            if (str.isTrue())
            {
                try
                {
                    IFormatter formatter = new BinaryFormatter();
                    byte[] buffer = Convert.FromBase64String(str);
                    MemoryStream stream = new MemoryStream(buffer);
                    obj = (T)formatter.Deserialize(stream);
                    stream.Flush();
                    stream.Close();
                }
                catch (Exception ex)
                {
                    throw new Exception("反序列化失败,原因:" + ex.Message);
                }
            }

            return obj;
        }

    }
    public class SerializeXml
    {
        //参数1 路径，path = Application.dataPath + "StreamingAssets/AAA/1.xml";
        //参数2 需要保存的类，    [Serializable]
        //参数3 是否需要替换
        public void CreateWriteXML<T>(string path, T t, bool isRelace)
        {
            string data = Serialize(t);  // 将类对象转换为 字符串
            CreateWriteFile(path, data, isRelace);
        }
        //参数1 路径，path = Application.dataPath + "StreamingAssets/AAA/1.xml";
        public T ReadXmlFile<T>(string path)
        {
            List<string> dataList = new List<string>();
            string data = "";
            dataList = ReadTxtFile(path, dataList);

            foreach (string str in dataList)
            {
                data += str;
            }

            T t = (T)Desrialize<T>(data);

            return t;
        }

        // 创建写入文件 ， 参数1 文件路径， 参数 2 写入信息, 参数3 是否删除之前的重新创建
        private static void CreateWriteFile(string path, string info, bool isRelace)
        {
            StreamWriter sw;
            FileInfo t = new FileInfo(path); //获取路径下文件信息

            if (t.Exists && isRelace)  //如果存在则删除
            {
                File.Delete(path);
            }

            if (!t.Exists)        //如果文件不存在则创建一个
            {
                sw = t.CreateText();
            }
            else
            {
                sw = t.AppendText();
            }
            sw.WriteLine(info);   //写入信息
            sw.Close();
            sw.Dispose();
        }
        //读取文件， 参数1 文件路径， 参数2 保存路径的集合
        private static List<string> ReadTxtFile(string path, List<string> saveList)
        {
            FileInfo info = new FileInfo(path);  //获取路径下文件信息
            if (!info.Exists)   //如果不存在返回
            {
                Debug.Log("!exist    " + path);
                return saveList;
            }

            StreamReader sr = null;
            sr = File.OpenText(path);  //存在则打开文件

            string line;
            while ((line = sr.ReadLine()) != null)  // 一行一行读取文件
            {
                saveList.Add(line);    //向保存文件集合添加 路径字符串
            }

            sr.Close();
            sr.Dispose();

            return saveList;
        }


        // 保存xml 前先将 类对象转换为 字符串      [Serializable]
        public static string Serialize<T>(T pObject)
        {
            if (pObject.isNull())
            {
                debug.log("Serialize obj is null!!!");
                return "";
            }
            try
            {
                string XmlizedString = null;
                MemoryStream memoryStream = new MemoryStream();
                //XmlSerializer xs = new XmlSerializer(typeof(UserData));
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xs.Serialize(xmlTextWriter, pObject);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                return XmlizedString;
            }
            catch (System.Exception ex)
            {
                debug.log("序列化失败,原因:" + ex.Message);
                return "";
            }
        }
        // 将读取的xml字符串转换为 类对象     [Serializable]
        public static T Desrialize<T>(string pXmlizedString)
        {
            T t = default(T);
            if (pXmlizedString.isTrue())
            {
                try
                {
                    //XmlSerializer xs = new XmlSerializer(typeof(UserData));
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                    t = (T)xs.Deserialize(memoryStream);
                }
                catch (System.Exception ex)
                {
                    debug.log("反序列化失败,原因:" + ex.Message);
                }
            }
            return t;
        }

        private static string UTF8ByteArrayToString(byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            string constructedString = encoding.GetString(characters);
            return (constructedString);
        }

        private static byte[] StringToUTF8ByteArray(string pXmlString)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] byteArray = encoding.GetBytes(pXmlString);
            return byteArray;
        }



    }

}